var urlArgs = Suningmatch.getUrlArgs();
var query = location.search.substring(1);

var vm = new Vue({
    el: '#home',
    data: {
        user: {},
        topic: {
        	"supNum": 0,
        	"rejNum": 0
        },
        zhengnum: 0,
        bestCommList: [],
        commTotal: 0,
        commList: [],
        criticType: 1,
        showPop: false,
        delPop: false,
        aboutPop: false,
        delCommId: "",
        tipPop: false,
        showLoading: false,
        pageNo: 1,
        pageSize: 0,
        uploadPop: false,
        plusClearObj: null,
        pointPop: false,
        pointTip: "",
        delIdx: 0,
        vPoint: ""
    },
    computed: {
        zheng: function() {
            var num = this.topic.supNum,
                total = num + this.topic.rejNum;
            this.zhengnum = total <= 0 ? 0 : parseInt((Math.ceil(num / total * 10000) / 100), 10);
            if(num == 0 && this.topic.rejNum == 0) {
                this.zhengnum = 50;
            }
            return this.zhengnum == 0 ? "0%" : this.zhengnum + "%";
        },
        fan: function() {
            var res = 100 - parseInt(this.zhengnum);
            return res + "%";
        }
    },
    methods: {
        alltopic: function() {
            location.href = "all_contend.html?topicId=" + urlArgs.topicId;
        },
        about: function() {
            vm.showPop = true;
            vm.delPop = false;
            vm.tipPop = false;
            vm.aboutPop = true;
        },
        topicVote: function(pointType) {
            if(vm.topic.viewPoint && vm.topic.viewPoint != "") {
                vm.pointPop = true;
                vm.pointTip = vm.topic.viewPoint == 1 ? "你已经" + vm.topic.supViewTip + "过了" : "你已经" + vm.topic.rejViewTip + "过了";
                setTimeout(function() {
                    vm.pointPop = false;
                    vm.pointTip = "";
                }, 2000);
                return;
            }
            vm.topic.viewPoint = pointType;
            var dataUrl = Suningmatch.DI.topicVote,
                dataObj = {
                    "topicId": urlArgs.topicId,
                    "viewPoint": vm.topic.viewPoint
                };
            if(this.criticType == 2) {
                dataUrl = Suningmatch.DI.WXtopicVote;
                dataObj = {
                    "topicId": urlArgs.topicId,
                    "openId": urlArgs.wx_openid,
                    "viewPoint": vm.topic.viewPoint
                };

            }
            $.ajax({
                type: "post",
                url: dataUrl,
                data: dataObj,
                dataType: "json",
                success: function(data) {
                    if(data != null && data.idsIntercepted == true) {
                        vm.oaOvertime();
                        return;
                    }
                    if(data.retFlag == 1) {
                        vm.pointPop = true;
                        vm.pointTip = "投票成功！";
                        vm.vPoint = pointType;
                        setTimeout(function() {
                            vm.pointPop = false;
                            vm.pointTip = "";
                        }, 2000);
                        if(pointType == 1) {
                            vm.topic.supNum = vm.topic.supNum + 1;
                            vm.topic.viewPoint = 1;
                        } else {
                            vm.topic.rejNum = vm.topic.rejNum + 1;
                            vm.topic.viewPoint = 2;
                        }
                        //如果是在弹框里面的正反，需要跳转页面
                        if(vm.showPop) {
                            vm.showPop = false;
                            vm.tipPop = false;
                            vm.aboutPop = false;
                            var locationURL = "white_comm.html?topicId=" + urlArgs.topicId;
                            location.href = locationURL;
                        }

                    }

                },
                error: function(err) {
                    console.log(err);
                }
            });
        },
        commVote: function(iszan, commId, idx, isbest) {
            clearTimeout(vm.plusClearObj);
            var plusObj = $(".best-comm .item .cnt").eq(idx).find(".zan .plus");
            var imgObj = $(".best-comm .item .cnt").eq(idx).find(".zan .zan-img");
            if(isbest) {
                if(iszan) {
                    plusObj = $(".best-comm .item .cnt").eq(idx).find(".zan .plus");
                    imgObj = $(".best-comm .item .cnt").eq(idx).find(".zan .zan-img");
                } else {
                    plusObj = $(".best-comm .item .cnt").eq(idx).find(".cai .plus");
                    imgObj = $(".best-comm .item .cnt").eq(idx).find(".cai .cai-img");
                }
            }
            if(!isbest) {
                if(iszan) {
                    plusObj = $(".normal-comm .item .cnt").eq(idx).find(".zan .plus");
                    imgObj = $(".normal-comm .item .cnt").eq(idx).find(".zan .zan-img");
                } else {
                    plusObj = $(".normal-comm .item .cnt").eq(idx).find(".cai .plus");
                    imgObj = $(".normal-comm .item .cnt").eq(idx).find(".cai .cai-img");
                }
            }
            if(imgObj.attr("src") == "img/zaned.png" || imgObj.attr("src") == "img/caied.png") {
                return;
            }
            if(iszan) {
                imgObj.attr("src", "img/zaned.png");
            } else {
                imgObj.attr("src", "img/caied.png");
            }
            plusObj.hide();
            $.ajax({
                type: "post",
                url: Suningmatch.DI.commVote,
                //              type: "get",
                //              url: "js/commont.json",
                data: {
                    "commId": commId,
                    "isZan": iszan
                },
                dataType: "json",
                success: function(data) {
                    if(data.retFlag == 1) {
                        if(iszan) {
                            imgObj.attr("src", "img/zan.png");
                        } else {
                            imgObj.attr("src", "img/cai.png");
                        }
                        plusObj.show();
                        vm.plusClearObj = setTimeout(function() {
                            plusObj.hide();
                        }, 500);
                        if(iszan) {
                            if(isbest) {
                                vm.bestCommList[idx].zanNum = vm.bestCommList[idx].zanNum + 1;
                            } else {
                                vm.commList[idx].zanNum = vm.commList[idx].zanNum + 1;
                            }

                        } else {
                            if(isbest) {
                                vm.bestCommList[idx].caiNum = vm.bestCommList[idx].caiNum + 1;
                            } else {
                                vm.commList[idx].caiNum = vm.commList[idx].caiNum + 1;
                            }
                        }
                    }
                },
                error: function(err) {
                    console.log(err);
                }
            });
        },
        delComm: function(commId, idx) {
            vm.showPop = true;
            vm.tipPop = false;
            vm.aboutPop = false;
            vm.delPop = true;
            vm.delCommId = commId;
            vm.delIdx = idx; //删除成功后需要用到
        },
        cancel: function() {
            vm.showPop = false;
            vm.delPop = false;
            vm.tipPop = false;
            vm.aboutPop = false;
        },
        ok: function() {
            var dataUrl = Suningmatch.DI.delComm,
                dataObj = {
                    "commId": vm.delCommId
                }
            if(this.criticType == 2) {
                dataUrl = Suningmatch.DI.WXdelComm,
                    dataObj = {
                        "commId": vm.delCommId,
                        'openId': urlArgs.wx_openid
                    }
            }
            $.ajax({
                type: "post",
                url: dataUrl,
                data: dataObj,
                dataType: "json",
                success: function(data) {
                    if(data != null && data.idsIntercepted == true) {
                        vm.oaOvertime();
                        return;
                    }
                    if(data.retFlag == 1) {
                        vm.showPop = false;
                        vm.delPop = false;
                        vm.commList.splice(vm.delIdx, 1); //删除成功后页面控制删掉 不用重新刷新数据
                    } else {
                        console.error("+error")
                    }

                },
                error: function(err) {
                    console.log(err);
                }
            });
        },
        whitecomm: function() {
            if(vm.topic.viewPoint == 1 || vm.topic.viewPoint == 2) {
                var locationURL = "white_comm.html?topicId=" + urlArgs.topicId;
                location.href = locationURL;
            } else {
                vm.showPop = true;
                vm.delPop = false;
                vm.tipPop = true;
            }
        },
        addList: function(n) {
            var dataUrl = Suningmatch.DI.getComm,
                dataObj = {
                    'start': vm.pageSize,
                    'limit': 10,
                    'topicId': urlArgs.topicId
                }
            if(this.criticType == 2) {
                dataUrl = Suningmatch.DI.WXgetComm,
                    dataObj = {
                        'start': vm.pageSize,
                        'limit': 10,
                        'topicId': urlArgs.topicId,
                        'openId': urlArgs.wx_openid
                    }
            }
            $.ajax({
                type: "post",
                url: dataUrl,
                //              type: "get",
                //              url: "js/commont.json",
                dataType: "json",
                data: dataObj,
                beforeSend: function() {
                    vm.showLoading = true;
                },
                success: function(commData) {
                    if(commData != null && commData.idsIntercepted == true) {
                        vm.oaOvertime();
                        return;
                    }
                    vm.showLoading = false;
                    var comms = commData.data;
                    if(comms.bestCommList) {
                        vm.bestCommList = comms.bestCommList;
                    } else {
                        vm.bestCommList = [];
                    }
                    if(comms.commList) {
                        vm.commTotal = comms.commList.total;
                        var data = comms.commList.rows;
                        if(n == 0) {
                            vm.commList = data;
                        } else {
                            for(var i = 0; i < data.length; i++) {
                                vm.commList.push(data[i]);
                            }
                        }
                        vm.pageSize += data.length;
                    }
                },
                error: function(err) {
                    console.log(err);
                }
            });
        },
        closePop: function() {
            vm.showPop = false;
            vm.delPop = false;
            vm.tipPop = false;
        },
        replaceImg: function() {
            setTimeout(function() {
                vm.uploadPop = true;
            }, 1000);

            cropperImg();
        },
        cancle: function() {
            vm.uploadPop = false;
        },
        uploadImg: function() {
            //调用上传图片接口
            var x = $("#preview-x").val(),
                y = $("#preview-y").val(),
                width = $("#preview-width").val(),
                height = $("#preview-height").val();

            var canvas = $('<canvas style="display:none;" width="' + width + '" height="' + height + '"></canvas>')[0],
                ctx = canvas.getContext('2d');
            ctx.drawImage(Suningmatch.cropper, x, y, width, height, 0, 0, width, height);
            var data = canvas.toDataURL();
            // dataURL 的格式为 “data:image/png;base64,****”,逗号之前都是一些说明性的文字，我们只需要逗号之后的就行了
            data = data.split(',')[1];
            data = window.atob(data);
            var ia = new Uint8Array(data.length);
            for(var i = 0; i < data.length; i++) {
                ia[i] = data.charCodeAt(i);
            };
            // canvas.toDataURL 返回的默认格式就是 image/png
            var blob = new Blob([ia], {
                type: "image/png"
            });
            var fd = new FormData();
            fd.append('image', blob);
            $.ajax({
                type: "post",
                url: Suningmatch.DI.uploadMisc,
                dataType: "json",
                data: fd,
                contentType: false, //不可缺
                processData: false, //不可缺
                success: function(response) {
                    if(response != null && response.idsIntercepted == true) {
                        vm.oaOvertime();
                        return;
                    }
                    if(response.retFlag == 1) {
                    	var hpic = ""
                    	if (location.host.indexOf("dj.suning.com") != -1) {
                    		hpic= "http://image?.suning.cn" + response.data;
                    	} else {
                    		hpic= "http://uimgpre.cnsuning.com" + response.data;
                    	}
                        hpic = Suningmatch.imgprefix(hpic);
                        vm.user.nickimg = hpic;
                        $.ajax({
                            type: "post",
                            url: Suningmatch.DI.modifyUserHeadPic,
                            dataType: "json",
                            data: {
                                "headPic": hpic
                            },
                            success: function(modifyResponse) {
                                if(modifyResponse != null && modifyResponse.idsIntercepted == true) {
                                    vm.oaOvertime();
                                    return;
                                }
                                if(modifyResponse.retFlag == 1) {
                                    vm.uploadPop = false;
                                }
                            },
                            error: function(err) {
                                console.log(err);
                            }
                        });
                    }
                },
                error: function(err) {
                    console.log(err);
                }
            });
        },
        getTopic: function() {
            var dataObj = {
                    "headPic": urlArgs.wx_headimgurl,
                    "nickname": urlArgs.wx_nickname,
                    "openId": urlArgs.wx_openid,
                    "topicId": urlArgs.topicId
                },
                dataURL = Suningmatch.DI.getTopic;
            if(this.criticType == 1) {
                dataObj = {
                    "topicId": urlArgs.topicId
                };
                dataURL = Suningmatch.DI.getTopicforOA;
            }
            $.ajax({
                type: "post",
                url: dataURL,
                //          type: "get",
                //          url: "js/topic.json",
                data: dataObj,
                dataType: "json",
                success: function(response) {
                    if(response != null && response.idsIntercepted == true) {
                        vm.oaOvertime();
                        return;
                    }
                    //test
                    //vm.topic = response.data[0];
                    vm.topic = response.data;
                    vm.vPoint = vm.topic.viewPoint;
                    vm.addList(0);
                },
                error: function(err) {
                    console.log(err);
                }
            });
        }
    },
    ready: function() {
        if(window.navigator.userAgent.indexOf("MSIE") >= 1 || !!window.ActiveXObject || "ActiveXObject" in window) {
            alert('非常抱歉，时间有限，暂不支持IE浏览器，请使用其它浏览器打开');
            return;
        }
        var ua = window.navigator.userAgent.toLowerCase();
        if(ua.match(/MicroMessenger/i) == 'micromessenger') {
            if(location.href.indexOf("wx_openid") == -1) {
                location.href = Suningmatch.wxLogin + encodeURIComponent(location.href);
            }
            this.criticType = 2;
            this.user = {
                nickname: urlArgs.wx_nickname,
                nickimg: urlArgs.wx_headimgurl
            };
            this.getTopic();
        } else {
            this.criticType = 1;
            if(location.href.indexOf("isLogin") == -1) {
                location.href = Suningmatch.DI.soaTopic + "?redirectUrl=" + location.href;
            }
            $.ajax({
                type: "post",
                url: Suningmatch.DI.getLoginInfo,
                dataType: "json",
                success: function(response) {
                    if(response != null && response.idsIntercepted == true) {
                        location.href = Suningmatch.DI.soaTopic + "?redirectUrl=" + location.href;
                    }
                    var userData = response.data;
                    vm.user = {
                        nickname: userData.personName,
                        nickimg: userData.headPic
                    }
                    vm.getTopic();
                },
                error: function(err) {
                    console.log(err);
                }
            });
        }

    }
});